package com.speak.sparkadminserver.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.speak.sparkadminserver.domain.NutRole;
import com.speak.sparkadminserver.domain.NutUser;
import com.speak.sparkadminserver.service.NutRolePowerService;
import com.speak.sparkadminserver.service.NutRoleService;
import com.speak.sparkadminserver.service.NutUserService;
import com.speak.sparkadminserver.utils.Result;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @version 1.0
 * @Author Xing
 * @Date 2023/2/18 11:44
 */
@RestController
@RequestMapping("/admin")
public class NutUserController {
    @Autowired
    private NutUserService nutUserService;
    @Autowired
    private StringRedisTemplate template;
    @Autowired
    private static final ObjectMapper mapper = new ObjectMapper();
    @Autowired
    private NutRoleService roleService;
    @Autowired
    private NutRolePowerService powerService;
    @GetMapping("/login")
    public Result login(@Param("user") NutUser user) throws JsonProcessingException {
        NutUser user1;
        try{
            user1 = nutUserService.getUser(user.getUsername());
        }catch (Exception e){
            return Result.err(401,"账号或密码错误");
        }
        if (!user1.getPassword().equals(user.getPassword())){
            return Result.err(401,"账号或密码错误");
        }
        String token = UUID.randomUUID().toString().replace("-", "");
        String json = mapper.writeValueAsString(user1);
        template.opsForValue().set("token:"+token,json,4L, TimeUnit.HOURS);
        return Result.ok(token);
    };

    @GetMapping("register")
    public Result Register(@Param("user") NutUser user) throws JsonProcessingException {
        System.out.println(user);
        boolean usersNumber = nutUserService.getUsersNumber(user.getUsername());
        boolean save;
        try {
            if (usersNumber){
                nutUserService.save(user);
            }else {
                return Result.err(301,"注册失败");
            }
        }catch (Exception e) {
            System.out.println(e);
            return Result.err(301,"注册失败");
        }
        String token = UUID.randomUUID().toString().replace("-", "");
        String json = mapper.writeValueAsString(user);
        template.opsForValue().set("token:"+token,json,4L, TimeUnit.HOURS);
        return Result.ok(token);
    };
    @GetMapping("/add")
    @PreAuthorize("hasAnyAuthority('1')")
    public Result add(@Param("user") NutUser user){
        boolean usersNumber = nutUserService.getUsersNumber(user.getUsername());
        boolean save;
        try {
            if (usersNumber){
                nutUserService.save(user);
                Long id = nutUserService.getId(user.getUsername());
                roleService.SaveUserRole(id);
                Long aLong = roleService.GetroleId(id);
                powerService.Save(aLong);
            }else {
                return Result.err(306,"添加失败");
            }
        }catch (Exception e) {
            System.out.println(e);
            return Result.err(306,"添加失败");
        }
        return Result.ok("添加成功");
    }

    @GetMapping("/all")
    @PreAuthorize("hasAnyAuthority('3')")
    //查看所有用户
    public Result all(@RequestParam Map<String,Object> map){
        Page all = nutUserService.getAll(map);
        return Result.ok(all);
    }
    @PostMapping("power")
    public Result AddPower(@RequestParam("map") Map<String,String> map){
        return null;
    }
    @PostMapping("test")
    @PreAuthorize("hasAnyAuthority('3')")
    public Result AddTest(){
        return Result.ok("成功");
    }

    @PostMapping("logout")
    public Result Logout(@RequestBody Map<String,String> map){
        UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken)
                SecurityContextHolder.getContext().getAuthentication();
        User user = (User) authenticationToken.getPrincipal();
        System.out.println(map.get("token"));
        Boolean delete = template.delete("token:" + map.get("token"));
        if (delete){
            return Result.ok("登出成功");
        }
        return Result.err(302,"登出失败");
    }
    @GetMapping("update")
    @PreAuthorize("hasAnyAuthority('1')")
    public Result Update(@Param("user") NutUser user){
        System.out.println(user);
        boolean usersNumber = nutUserService.getUsersNumber(user.getUsername());
        boolean b = false;
        try {
            b=nutUserService.saveOrUpdate(user);
        }catch (Exception e){
            System.out.println(e);
        }
        if (!usersNumber&&b){
            return Result.ok("修改成功");
        }
        return Result.err(303,"修改失败");
    }

    @DeleteMapping("delById")
    @PreAuthorize("hasAnyAuthority('1')")
    public Result Delete(@Param("id") Long id){
        boolean b=false;
        NutUser byId = nutUserService.getById(id);
        byId.setDelFlag(1);
        try {
            b = nutUserService.saveOrUpdate(byId);
        }catch (Exception e){
            System.out.println(e);
        }
        if (b){
            return Result.ok("删除成功");
        }else {
            return Result.err(304,"删除失败");
        }

    }
    @PostMapping("status")
    @PreAuthorize("hasAnyAuthority('1')")
    public Result status(@RequestBody Map<String,Object> map){
        long id = Long.parseLong((String) map.get("id"));
        Boolean status = (Boolean) map.get("status");
        NutUser byId = nutUserService.getUserById(id);
        System.out.println(byId);
        try {
            byId.setStatus(status);
            nutUserService.saveOrUpdate(byId);
        }catch (Exception e){
            System.out.println(e);
            return Result.err(306,"修改失败");
        }
        return Result.ok();
    }

    @GetMapping("auth")
    public List<Integer> AuthList(Long userId){
        return powerService.AuthList(userId);
    }
}
